package com.javaweb.dao.impl;

import com.javaweb.dao.ArticleDao;
import com.javaweb.model.Article;
import com.javaweb.model.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.util.ObjectUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

@Repository
public class ArticleDaoImpl implements ArticleDao {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public int insert(Article article) {
        if (ObjectUtils.isEmpty(article) || ObjectUtils.isEmpty(article.getUserId()) ||
                ObjectUtils.isEmpty(article.getTitle()) || ObjectUtils.isEmpty(article.getContent()) ||
                ObjectUtils.isEmpty(article.getCategoryId())) {
            return 0; // 插入失败
        }

        String sql = "INSERT INTO tb_article (user_id, title, content, status, " +
                "description, category_id, create_time, update_time)" +
                " VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        Object[] args = new Object[]{
                article.getUserId(),
                article.getTitle(),
                article.getContent(),
                article.getStatus(),
                article.getDescription(),
                article.getCategoryId(),
                new java.sql.Date(article.getCreateTime().getTime()),
                new java.sql.Date(article.getUpdateTime().getTime())};

        return jdbcTemplate.update(sql, args) > 0 ? 1 : 0; // 返回插入结果
    }

    @Override
    public int updateContent(Integer id, String newContent) {
        if (ObjectUtils.isEmpty(id) || ObjectUtils.isEmpty(newContent)) {
            return 0; // 更新失败
        }
        String sql = "UPDATE tb_article SET content = ?, update_time = NOW() WHERE id = ?";
        return jdbcTemplate.update(sql, newContent, id) > 0 ? 1 : 0; // 返回更新结果
    }

    @Override
    public int updateTitle(Integer id, String newTitle) {
        if (ObjectUtils.isEmpty(id) || ObjectUtils.isEmpty(newTitle)) {
            return 0; // 更新失败
        }
        String sql = "UPDATE tb_article SET title = ?, update_time = NOW() WHERE id = ?";
        return jdbcTemplate.update(sql, newTitle, id) > 0 ? 1 : 0; // 返回更新结果
    }

    @Override
    public int deleteById(Integer id) {
        if (ObjectUtils.isEmpty(id)) {
            return 0; // 删除失败
        }
        String sql = "DELETE FROM tb_article WHERE id = ?";
        return jdbcTemplate.update(sql, id) > 0 ? 1 : 0; // 返回删除结果
    }

    @Override
    public List<Article> selectByUserId(Integer userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return null; // 返回 null
        }

        String sql = "SELECT * FROM tb_article WHERE user_id = ? ORDER BY create_time DESC";
        List<Article> articles = jdbcTemplate.query(sql, new Object[]{userId}, new ArticleRowMapper());
        return articles.isEmpty() ? null : articles; // 返回查询结果
    }

    @Override
    public List<Article> selectByKeyword(String keyword) {
        if (ObjectUtils.isEmpty(keyword)) {
            return null; // 返回 null
        }
        String sql = "SELECT * FROM tb_article WHERE title LIKE ? OR content LIKE ? ORDER BY create_time DESC";
        List<Article> articles = jdbcTemplate.query(sql, new Object[]{"%" + keyword + "%", "%" + keyword + "%"},
                new ArticleRowMapper());
        return articles.isEmpty() ? null : articles; // 返回查询结果
    }

    @Override
    public List<Article> selectByTimePeriod(Date startTime, Date endTime) {
        StringBuilder sql = new StringBuilder("SELECT * FROM tb_article WHERE 1=1");
        List<Object> params = new ArrayList<>();

        if (startTime != null) {
            sql.append(" AND create_time >= ?");
            params.add(new java.sql.Date(startTime.getTime()));
        }
        if (endTime != null) {
            sql.append(" AND create_time <= ?");
            params.add(new java.sql.Date(endTime.getTime()));
        }
        sql.append(" ORDER BY create_time DESC");

        List<Article> articles = jdbcTemplate.query(sql.toString(), params.toArray(), new ArticleRowMapper());
        return articles.isEmpty() ? null : articles; // 返回查询结果
    }

    @Override
    public List<Article> selectByTag(Integer tagId) {
        if (ObjectUtils.isEmpty(tagId)) {
            return null; // 返回 null
        }

        String sql = "SELECT a.* FROM tb_article a " +
                "JOIN tb_article_tag at ON a.id = at.article_id " +
                "WHERE at.tag_id = ? ORDER BY a.create_time DESC";
        List<Article> articles = jdbcTemplate.query(sql, new Object[]{tagId}, new ArticleRowMapper());
        return articles.isEmpty() ? null : articles; // 返回查询结果
    }

    @Override
    public List<Article> selectByCategory(Integer categoryId) {
        if (ObjectUtils.isEmpty(categoryId)) {
            return null; // 返回 null
        }

        String sql = "SELECT * FROM tb_article WHERE category_id = ? ORDER BY create_time DESC";
        List<Article> articles = jdbcTemplate.query(sql, new Object[]{categoryId}, new ArticleRowMapper());
        return articles.isEmpty() ? null : articles; // 返回查询结果
    }

    private static class ArticleRowMapper implements RowMapper<Article> {
        @Override
        public Article mapRow(ResultSet rs, int rowNum) throws SQLException {
            Article article = new Article();
            article.setId(rs.getInt("id"));
            article.setUserId(rs.getInt("user_id"));
            article.setTitle(rs.getString("title"));
            article.setContent(rs.getString("content"));
            article.setStatus(rs.getInt("status"));
            article.setDescription(rs.getString("description"));
            article.setCategoryId(rs.getInt("category_id"));
            article.setCreateTime(rs.getDate("create_time"));
            article.setUpdateTime(rs.getDate("update_time"));
            return article;
        }
    }
}
